package com.zhengsr.latte.net.download;

import android.os.AsyncTask;

import com.zhengsr.latte.net.RestClient;
import com.zhengsr.latte.net.RestCreator;
import com.zhengsr.latte.net.RestService;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by zhengshaorui on 2018/4/11.
 */

public class DownloadHanlder {
    private RestClient.Builder mBuilder;

    public DownloadHanlder(RestClient.Builder builder) {
        this.mBuilder = builder;
        RestService service = RestCreator.getService();
        retrofit2.Call<ResponseBody> call = service.download(mBuilder.url,builder.params);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()){
                   SaveFileTask task =  new SaveFileTask();
                   task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                            mBuilder,response.body());

                   //判断文件是否下载完成
                    if (task.isCancelled()){
                        if (mBuilder != null){
                            if (mBuilder.listenerAdapter != null){
                                mBuilder.listenerAdapter.onRequestEnd();
                            }
                        }
                    }
                }else{
                    if (mBuilder != null){
                        if (mBuilder.listenerAdapter != null){
                            mBuilder.listenerAdapter.onError(response.code(),response.message());
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                if (mBuilder != null){
                    if (mBuilder.listenerAdapter != null){
                        mBuilder.listenerAdapter.onFailure(t.toString());
                    }
                }
            }
        });
    }

}
